import * as api from '../../api/api.js';
const {
  getPlayletManager
} = tt;
const app = getApp();
const os = app.os;

Component({
  pm: undefined,
  adTimerId: 0,
  seeTimerId: 0,
  data: {
    appType: app.globalData.appType,
    iaaMix: app.globalData.iaaMix, //免费版混合付费
    swiperHeight: 0,
    showAdUnlockMask: false,
    isTrySee: false,
    unlockBtnTitle: '看广告解锁',
    countdown: app.globalData.adCountdown, //倒数读秒
    timeCount: app.globalData.adCountdown, //填写同上
    currentVideo: false,
    vipRechargeData: false
  },
  properties: {
      seq: {
          type: Number,
          value: 1
      },
      albumId: {
          type: String
      },
      episodeId: {
          type: String
      }
  },
  // inject: ["seq"], 
  observers: {
    seq(val) {
      const _this = this;
      const currentVideo = this.getCurrentVideo(val);
      app.echo("player", val, currentVideo, app.playerData);

      this.setData({
        countdown: app.globalData.adCountdown,
        timeCount: app.globalData.adCountdown
      });

      this.showUnlockBtn();
      const { showAdBtn, isUnlockPreview } = app.playerData;
      if (currentVideo !== false) {
        const showAdUnlockMask = (app.globalData.appType === 2 || isUnlockPreview === true) ? false:(currentVideo.is_unlock !== 1 ? false:showAdBtn);
        if (showAdUnlockMask) {
          this.data.isTrySee = true;
          app.eventer.emit('onAdUnlockEvent', {type: 3});
          this.seeTimerId = setTimeout(function(){
            app.eventer.emit('onAdUnlockEvent', {type: 4});
            _this.data.isTrySee = false;
            _this.setData({
              isTrySee: _this.data.isTrySee
            });
          }, this.data.timeCount * 1000);
        }
        this.setData({
          isTrySee: this.data.isTrySee,
          iaaMix: app.globalData.iaaMix,
          appType: app.globalData.appType,
          currentVideo: currentVideo,
          showAdUnlockMask: showAdUnlockMask
        });
        
        if (showAdUnlockMask) {
          if (currentVideo.chapter_unlock_num > 0) {
            app.eventer.emit('onAdUnlockEvent', {type: 'showBenefitAd', data: currentVideo});
          } else {
            this.autoPullupAd();
          }
        }
        if (app.globalData.iaaMix) {
          this.getRechargeList();
        }
      }
    },
  },
  ready() {
    const pm = getPlayletManager();
    this.pm = pm;

    app.eventer.on('onPlayerPageEvent', this.onPlayerPageEvent.bind(this));

    // 点击解锁按钮
    pm.onClickUnlock((e) => {
      app.echo("触发点击解锁按钮onClickUnlock回调:" , JSON.stringify(e,null,2), this.data)
      if (app.globalData.appType === 1) {
        this.showUnlockBtn(e.seq);
        this.setData({
          showAdUnlockMask: true
        })
      }
    });

    // 切换剧集
    pm.onChangeEpisode((e) => {
      app.echo("触发选集切换onChangeEpisode回调:", JSON.stringify(e, null, 2));
      if (e.seq !== this.properties.seq) {
        this.clearAdTimer();
        this.clearSeeTimer();
      }
    })

    // 点击控件
    pm.onControlTap((e) => {
      const _this = this;
      switch (e.controlType) {
        case "subscribe":
          this.onBingePopCancel();
          break;
      
        default:

          break;
      }
    });

    // 播放事件
    pm.onPlay((e) => {
      if (e.seq === this.properties.seq && this.data.isTrySee === false) {
        this.setData({
          showAdUnlockMask: false
        })
      }
    });

    // 视频高度
    const query = os.createSelectorQuery()
    query.select('#playlet-swiper').boundingClientRect()
    query.exec((res) => {
      if (res[0]) {
        if (res[0].height > 0) {
          this.setData({
            swiperHeight: res[0].height,
          });
        }
      } 
    });
  },

  methods: {
    /**
     * 获取当前集
     */
    getCurrentVideo(seq = 1) {
      let { currentAblum,currentVideo } = app.playerData;
      if (currentAblum !== false) {
        currentVideo = currentAblum.list.find(item => item.num === seq);
        if (currentVideo !== undefined) {
          Object.assign(currentVideo,{
            follow: currentAblum.follow,
            is_collect: currentAblum.is_collect,
            playlet_name: currentAblum.playlet_name,
            ad_unlock_num: currentAblum?.ad_unlock_num || 1
          });
          this.data.currentVideo = currentVideo;
          return currentVideo;
        }
      }
      return false;
    },

    /**
     * 下次再说
     */
    closeUnlockBtn() {
      if (this.data.isTrySee === true) {
        app.eventer.emit('onAdUnlockEvent', {type: 4});
        this.data.isTrySee = false;
        this.setData({
          isTrySee: this.data.isTrySee
        });
      }

      if (this.pm) {
        app.playerData.showAdBtn = false
        this.pm.setConfig({
          showLockPage: true
        })
        this.setData({
          showAdUnlockMask: false
        })
        this.clearAdTimer()
      }
    },

    /**
     * 显示广告解锁
     */
    showUnlockBtn(seq = -1) {
      if (app.globalData.appType === 1) {
        if (this.pm) {
          app.playerData.showAdBtn = true
          this.pm.setConfig({
            showLockPage: false
          })
          if (seq > -1) {
            const currentVideo = this.getCurrentVideo(seq);
            if (currentVideo?.chapter_unlock_num == 0) {
              this.autoPullupAd();
            }
          }
        }
      }
    },

    /**
     * 自动拉起广告
     */
    autoPullupAd() {
      const _this = this;
      const timeCount = this.data.timeCount;
      if (app.globalData.appType === 1) {
        if (this.adTimerId > 0) {
          clearInterval(this.adTimerId);
        }
        this.data.countdown = timeCount;
        this.setData({
          unlockBtnTitle: `${timeCount}s后拉起广告`
        });
        this.adTimerId = setInterval(function(){
          const countdown = _this.data.countdown - 1;
          if(countdown <= 0){
            _this.clearAdTimer();
            _this.onAdUnlockEvent();
            return;
          }
          _this.data.countdown = countdown;
          _this.setData({
            unlockBtnTitle: `${countdown}s后拉起广告`
          });
        }, 1000);
        app.echo('adTimerId: ', this.adTimerId);
      }
    },
    
    clearSeeTimer(){
      if (this.seeTimerId > 0) {
        clearTimeout(this.seeTimerId);
        this.seeTimerId = 0;
      }
    },

    clearAdTimer(){
      // if (this.data.showAdUnlockMask) {
        if (this.adTimerId > 0) {
          clearInterval(this.adTimerId);
          this.adTimerId = 0;
        }
        this.setData({
          unlockBtnTitle: '立即解锁'
        });
      // }
    },

    /**
     * 立即解锁
     */
    onAdUnlockEvent() {
      this.clearAdTimer();
      app.eventer.emit('onAdUnlockEvent', {type: 1});
    },

    /**
     * 免广告解锁
     */
    adFreeUnlock() {
      this.clearAdTimer();
      app.eventer.emit('onAdUnlockEvent', {type: 2});
    },

    /**
     * 返回
     */
    onClickBackBtn(){
      app.eventer.emit('onAdUnlockEvent', {type: 5});
    },

    /**
     * 获取充值模板
     */
    getRechargeList(){
      const { currentVideo,vipRechargeData } = this.data;
      if (currentVideo === false || vipRechargeData !== false) {
        return;
      }
      api.getRechargeList({
        playlet_id: currentVideo?.playlet_id || 0,
      }, {showErr: false}).then(res => {
        if (res.code == 200 && res.data?.vip_list?.length > 0) {
          app.echo('api getRechargeList', res, res?.data?.vip_list[0]);
          this.setData({
            vipRechargeData: res?.data?.vip_list[0],
          });
        }
      });
    },

    /**
     * 接受其他页面传来的数据
     */
    onPlayerPageEvent(res) {
      app.echo('onPlayerPageEvent', res);
      console.log('onPlayerPageEvent', res);
      const { type } = res;
      switch (type) {
        case 'closeAd':
          this.autoPullupAd();
          break;
      }
    }

  }
})